<?php

namespace App\Services\Traits;

use App\Exceptions\CreateDataException;

trait ModelOperatorTrait{

	protected function get($query, $conditions, $fillable = null){
		if(is_array($fillable) && !is_null($fillable) && count($fillable) > 0){
			$conditions = array_only($conditions, $fillable);
		}

		foreach ($conditions as $key => $value) {
			$query->where($key, $value);
		}

		return $query;
	}

	protected function like($query, $conditions, $fillable = null){
		if(is_array($fillable) && !is_null($fillable) && count($fillable) > 0){
			$conditions = array_only($conditions, $fillable);
		}

		foreach ($conditions as $key => $value) {
			$query->where($key,'like','%'.$value.'%');
		}

		return $query;
	}

	protected function not($query, $conditions, $fillable = null){
		if(is_array($fillable) && !is_null($fillable) && count($fillable) > 0){
			$conditions = array_only($conditions, $fillable);
		}
		foreach ($conditions as $key => $value) {
			$query->where($key,'!=',$value);
		}
		return $query;
	}

	protected function findModelByNot($model, $query, $conditions, $first = false){
		$model = new $model;

		$fillable = $model->getFillable();
		
		array_push($fillable, $model->getKeyName());

		$query = $this->not($query, $conditions, $fillable);
		return $query;
	}

	protected function findModel($model, $query, $conditions, $first = false, $isLike = false){

		$model = new $model;

		$fillable = $model->getFillable();
		array_push($fillable, $model->getKeyName());

		if($conditions != null){
			if($isLike){
				$query = $this->like($query, $conditions, $fillable);
			}
			else{
				$query = $this->get($query, $conditions, $fillable);
			}
			
		}

		return $first? $query : $query->first();
	}

	protected function create($model,$data){

		$model = new $model;

		$fillable = $model->getFillable();

		$dataKey = array_keys($data);

		$arrayDiff = array_diff($dataKey,$fillable);
		
		if (count($arrayDiff) > 0) {
			throw new CreateDataException;
		}

		$model::create($data);
	}

	protected function update($model,$id,$data){

		$model = new $model;

		$fillable = $model->getFillable();

		$dataKey = array_keys($data);

		$arrayIntersect = array_intersect($dataKey,$fillable);

		$updatedate = array_only($data,$fillable);

		$model::find($id)->update($updatedate);

	}
}
